<?php
/**
 * BootAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using BootAdmin.
 *
 * @Author G.r<root@BootAdmin.com>
 */

declare (strict_types=1);

namespace app\common\service;

use think\facade\Cache;
use think\helper\Str;

/**
 * Token服务
 */
class Token
{
    const TYPE_ADMIN = 'admin';

    const TYPE_USER = 'user';

    /**
     * 生成Token
     * @param int $id
     * @param string $type
     * @param int $expire
     * @return string
     */
    public function setToken(int $id, string $type, int $expire = 3600): string
    {
        $token = md5(Str::random(16));
        Cache::set("{$type}:{$token}", $id, $expire);
        return $token;
    }

    /**
     * 获取Token
     * @param string $token
     * @param string $type
     * @return int
     */
    public function getToken(string $token, string $type): int
    {
        return (int)Cache::get("{$type}:{$token}");
    }

    /**
     * 续签Token
     * @param string $token
     * @param string $type
     * @param int $expire
     * @return bool
     */
    public function overtimeToken(string $token, string $type, int $expire = 3600): bool
    {
        $id = Cache::get("{$type}:{$token}");
        if ($id) {
            Cache::set("{$type}:{$token}", $id, $expire);
            return true;
        }
        return false;
    }

    /**
     * 拉黑Token
     * @param string $token
     * @param string $type
     * @return bool
     */
    public function expireToken(string $token, string $type): bool
    {
        return Cache::delete("{$type}:{$token}");
    }
}